package com.itheima.pinda.service.impl;

import com.itheima.pinda.entity.fact.AddressRule;
import com.itheima.pinda.service.DroolsRuleService;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;

/**
 * @author llhuang10
 * @date 2021/10/12 10:59
 */
@Slf4j
// @Service     不需要加这个@Service注解 ? drools文件中会自动 new 出来这个对象
public class DroolsRuleServiceImpl implements DroolsRuleService {

    public static void main(String[] args) {
        DroolsRuleServiceImpl ruleService = new DroolsRuleServiceImpl();
        AddressRule addressRule = AddressRule.builder()
                .totalWeight(5)
                .firstWeight(1)
                .firstFee(20)
                .continuedFee(6).build();
        String calcFee = ruleService.calcFee(addressRule);
        System.out.println("calcFee = " + calcFee);
    }

    /**
     * 根据条件计算订单价格
     *
     * @param addressRule 封装计算订单价格所需的参数
     * @return 订单价格
     */
    @Override
    public String calcFee(AddressRule addressRule) {
        // 货物总重量
        BigDecimal totalWeight = BigDecimal.valueOf(addressRule.getTotalWeight());
        // 首重
        BigDecimal firstWeight = BigDecimal.valueOf(addressRule.getFirstWeight());
        // 首重价格
        BigDecimal firstFee = BigDecimal.valueOf(addressRule.getFirstFee());
        // 续重价格
        BigDecimal continuedFee = BigDecimal.valueOf(addressRule.getContinuedFee());

        // 超过首重部分重量 = 总重量 - 首重
        BigDecimal lost = totalWeight.subtract(firstWeight);
        // 只保留整数, 例如  3.5 -> 3   BigDecimal.ROUND_DOWN 舍入模式向零舍入, 不会增加计算值的大小
        lost = lost.setScale(0, BigDecimal.ROUND_DOWN);
        // 总价格 = 超出重量 * 续重价格 + 首重价格
        BigDecimal result = continuedFee.multiply(lost).add(firstFee);
        return result.toString();
    }
}
